const axios = require("axios");
const db = uniCloud.database();
exports.main = async (event, context) => {
	//event为客户端上传的参数
	console.log("event : ", event);

	// 获取所有用户
	let userList = await db.collection("userList").orderBy("createTime", "desc").get();

	let result = ''

	for (let i = 0; i < userList.data.length; i++) {
		let item = userList.data[i];

		if (item.serviceNotice) {
			console.log(event.data, 'event.data--------------------');
			let sendResult = sendMessage(
				item.openId,
				"fEm8kKmKVUASmZCyjHmrniw06a3EOnWBGnL27bgLhb8",
				event.data
			);
			
			if(sendResult.errcode != 0){
				let _id = item._id
				item.serviceNotice = false
				delete item['_id']
				await db.collection('userList').where({
					_id: _id
				}).update(item)
			}
		}
	}

	async function sendMessage(openId, template_id, data) {
		const pushmsg = {
			touser: openId, //要发送人的 optionId
			// VtKvZQf9OYESSBB_vE3Jpom0_eShd1tiN5X1uFsrR9M
			template_id: template_id, //消息通知模板
			data: data,
			miniprogram_state: "trial",
			lang: "zh_CN",
		};

		let send = await axios({
			url: `https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=${event.access_token}`,
			data: pushmsg,
			method: "POST",
			headers: {
				// 根据需要设置正确的 Content-Type  
				'Content-Type': 'application/json'
			}
		});

		console.log(send.data, 'send-=---------------------------');
		
		return send.data;
	}

	//返回数据给客户端
	return {
		code: 200,
		message: "发布成功"
	};
};